package com.kl.common.zookeeper;

import org.I0Itec.zkclient.ZkClient;

/**
 * 分布式锁
 *
 * @author staywood
 * @date 2018/04/21 22:41
 *
 */
public class DistributedLock {

    private static String servers = "120.27.108.62:2181";

    private static String LOCK_PARENT_PATH = "/sys/app_lock";

    private static String SYNCHRONIZED_STR = String.valueOf(System.currentTimeMillis());

    private static ZkClient zkClient;

    static{
        zkClient = new ZkClient(servers, 10000);
        boolean parentExist = existLock(LOCK_PARENT_PATH);
        if(!parentExist){
            zkClient.createPersistent(LOCK_PARENT_PATH, true);
        }
    }

    public static boolean existLock(String path){
        return zkClient.exists(path);
    }

    public static void getLock(String lockPath){
        synchronized (SYNCHRONIZED_STR){
            while(1 == 1){
                boolean exists = DistributedLock.existLock(LOCK_PARENT_PATH + "/" + lockPath);
                if(!exists){
                    try{
                        zkClient.createEphemeral(LOCK_PARENT_PATH + "/" + lockPath);
                        System.out.println("已经得到锁了");
                        break;
                    }catch (Exception e){
                        System.out.println("锁被其他客户端抢去了");
                    }
                }
                System.out.println("继续监听获取锁");
            }
        }
    }

    /**
     * 还锁
     * @param lockPath
     */
    public static void alsoLock(String lockPath){
        zkClient.delete(LOCK_PARENT_PATH + "/" +lockPath);
        System.out.println("已经还锁了");
    }
}
